import { EbbinghausPage, PageData } from '@/lib/EbbinghausPage';
import { AllInOneData } from '@/lib/FilterableEbbinghausPage';
import { loadYaml } from '@/lib/loadYaml';
import Link from 'next/link';

type PageProps = {
  params: {
    id: string;
  };
};

type LinkData = {
  href: string;
  text: string;
};

async function fetchPageData(id: string): Promise<{ data: PageData; links: LinkData[] }> {
  const { tags, data } = await loadYaml<AllInOneData>(`data/all-in-one.yml`);
  const tag = tags.find((x) => x.name === id) || { title: '', subtitle: '' };
  return {
    data: {
      title: tag.title,
      subtitle: tag.subtitle,
      data: (id === 'all' ? data : data.filter((x) => x.tag.includes(id))).map((x) => x.content),
    },
    links: tags.map((x) => ({
      href: `/${x.name}`,
      text: x.title,
    })),
  };
}

export async function generateStaticParams() {
  const { tags, data } = await loadYaml<AllInOneData>(`data/all-in-one.yml`);
  const links = tags.map((x) => x.name);
  return links.map((x) => ({ id: x }));
}

export async function generateMetadata({ params }: PageProps) {
  const { id } = params;
  const {
    data: { title, subtitle },
  } = await fetchPageData(id);
  return {
    title,
    description: '使用艾宾浩斯记忆法学习声律启蒙',
  };
}

export default async function Page({ params }: PageProps) {
  const { id } = params;
  const {
    data: { title, subtitle, data },
    links,
  } = await fetchPageData(id);
  return (
    <>
      <nav className='noprint'>
        <div className='p-5 flex-row gap-20' style={{ display: 'flex', flexDirection: 'row', gap: 20 }}>
          {links.map((x, i) => (
            <Link key={i} href={x.href}>
              {x.text}
            </Link>
          ))}
        </div>
      </nav>
      <main>
        <EbbinghausPage title={title} subtitle={subtitle} data={data} />
      </main>
    </>
  );
}
